package com.ucode.crm.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ucode.crm.builder.FollowupRecordBuilder;
import com.ucode.crm.dictionary.CrmResultDefineMsg;
import com.ucode.crm.dictionary.ModuleType;
import com.ucode.crm.dictionary.TeamUserPower;
import com.ucode.crm.mapper.BusinessMapper;
import com.ucode.crm.mapper.FollowupRecordMapper;
import com.ucode.crm.mapper.CrmTeamUserMapper;
import com.ucode.crm.mapper.OwnerChangeRecordMapper;
import com.ucode.crm.mode.Business;
import com.ucode.crm.mode.CrmTeamUser;
import com.ucode.crm.mode.OwnerChangeRecord;
import com.ucode.crm.service.BusinessService;
import com.ucode.tool.base.ResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.util.IdentifyUtils;
import cn.hutool.core.collection.CollUtil;

@Service
public class BusinessServiceImpl implements BusinessService {

    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private CrmTeamUserMapper followupTeamUserMapper;
    @Autowired
    private FollowupRecordMapper followupRecordMapper;
    @Autowired
    private FollowupRecordBuilder followupRecordBuilder;
    @Autowired
    private OwnerChangeRecordMapper ownerChangeRecordMapper;
    
    @Override
    @Transactional(rollbackFor=Exception.class)
    public Business insert(Business business) {
        
        Date now = new Date();
        business.setId(IdentifyUtils.getDefaultSnowflakeId());
        business.setCreatedTime(now);
        business.setUpdatedTime(now);
        businessMapper.insert(business);
        
        if(businessMapper.insert(business) == 0){
            throw new UcodeServiceException(ResultCodeEnum.FAILED);
        }
        
        List<CrmTeamUser> followupTeamUsers = new ArrayList<CrmTeamUser>();
        CrmTeamUser business_followTeamUser = new CrmTeamUser(business.getId(), ModuleType.business.code, business.getOwnerUserId(), TeamUserPower.owner.code);
        business_followTeamUser.setId(IdentifyUtils.getDefaultSnowflakeId());
        business_followTeamUser.setCreatedTime(now);
        business_followTeamUser.setUpdatedTime(now);
        
        if(business.getSynAdd().equals(0)){
            List<CrmTeamUser>  list = followupTeamUserMapper.findList(business.getCustomerId(), ModuleType.customer.code);
            if(CollUtil.isNotEmpty(list)){
                for(CrmTeamUser followupTeamUser : list){
                    if(followupTeamUser.getUserId().equals(business.getOwnerUserId()) || followupTeamUser.getUserId().equals(business.getCownerUserId()))
                        continue;
                    
                    CrmTeamUser contacts_followupTeamUser = new CrmTeamUser(business.getId(), ModuleType.business.code, followupTeamUser.getUserId(), followupTeamUser.getPower());
                    contacts_followupTeamUser.setId(IdentifyUtils.getDefaultSnowflakeId());
                    contacts_followupTeamUser.setCreatedTime(now);
                    contacts_followupTeamUser.setUpdatedTime(now);
                    followupTeamUsers.add(contacts_followupTeamUser);
                }
            }
        }
        
        followupTeamUserMapper.batchSave(followupTeamUsers);
        
        followupRecordMapper.insert(followupRecordBuilder.buildByBusiness(business));
        
        return business;
    }

    @Override
    public int update(Business business) {
        return businessMapper.update(business);
    }

    @Override
    public int deleteByLogic(Long id) {
        return businessMapper.deleteByLogic(id);
    }

    @Override
    public int delete(List<Long> ids) {
        return businessMapper.delete(ids);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int transfer(Long id, Long ownerUserId, Integer optType, Integer power, Long operatorId) {
        Business business = businessMapper.findById(id);
        
        if(business == null || business.getDeltag() == 1)
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        
        if(businessMapper.transfer(id, ownerUserId) == 0){
            throw new UcodeServiceException(ResultCodeEnum.FAILED.code,CrmResultDefineMsg.customer_pool_transfer_error,business.getName());
        }
        
        Date now = new Date();
        List<CrmTeamUser> followupTeamUsers = new ArrayList<CrmTeamUser>();
        List<OwnerChangeRecord> ownerChangeRecords = new ArrayList<OwnerChangeRecord>();
        
        //负责人变更记录
        OwnerChangeRecord business_ownerChangeRecord = new OwnerChangeRecord(business.getId(), ModuleType.business.code, business.getOwnerUserId(), ownerUserId, operatorId);
        business_ownerChangeRecord.setId(IdentifyUtils.getDefaultSnowflakeId());
        business_ownerChangeRecord.setCreatedTime(now);
        business_ownerChangeRecord.setUpdatedTime(now);
        ownerChangeRecords.add(business_ownerChangeRecord);
        
        //跟进团队
        CrmTeamUser business_followTeamOwnerUser = new CrmTeamUser(business.getId(), ModuleType.business.code, ownerUserId, TeamUserPower.owner.code);
        business_followTeamOwnerUser.setId(IdentifyUtils.getDefaultSnowflakeId());
        business_followTeamOwnerUser.setCreatedTime(now);
        business_followTeamOwnerUser.setUpdatedTime(now);
        followupTeamUsers.add(business_followTeamOwnerUser);
        
        CrmTeamUser business_oldOwner_FollowTeamOwnerUser = followupTeamUserMapper.find(business.getId(), ModuleType.business.code, business.getOwnerUserId());
        //移除原负责人
        if(optType.equals(0) && business_oldOwner_FollowTeamOwnerUser != null){
            followupTeamUserMapper.delete(business_oldOwner_FollowTeamOwnerUser.getId());
        }
        
        //将原负责人变为团队成员
        if(optType.equals(1) && business_oldOwner_FollowTeamOwnerUser != null){
            business_oldOwner_FollowTeamOwnerUser.setPower(power.intValue() == 2 ?TeamUserPower.readWrite.code:TeamUserPower.read.code);
            followupTeamUsers.add(business_oldOwner_FollowTeamOwnerUser);
        }
        
        if(ownerChangeRecords.size() > 0)
            ownerChangeRecordMapper.batchInsert(ownerChangeRecords);
        
        if(followupTeamUsers.size() > 0)
            followupTeamUserMapper.batchSave(followupTeamUsers);
        
        return 1;
    }

    @Override
    public Business findById(Long id) {
        return businessMapper.findById(id);
    }

    @Override
    public List<Business> findByIds(List<Long> ids) {
        return businessMapper.findByIds(ids);
    }


}
